/*
 * @Author: liu.lin liu.lin@hzleaper.com
 * @Date: 2023-11-07 13:45:22
 * @LastEditors: liu.lin liu.lin@hzleaper.com
 * @LastEditTime: 2023-11-08 17:08:43
 * @FilePath: \react_ts\src\pages\webscoket\index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Button } from "antd"
import { FC, useEffect, useState } from "react"
import { option } from "./option"
import * as echarts from "echarts"
import "./index.css"
import { number } from "echarts"
import * as Excel from "exceljs"
import * as FileSaver from "file-saver" //用于客户端读写数据

let wss: WebSocket
let heartCheck: string | number | NodeJS.Timeout | undefined
let connected = false // 添加连接状态标记

const ModeCode = {
  // websocket消息类型
  MSG: "message", // 普通消息
  HEART_BEAT: "heart_beat", // 心跳
}

// 这个页面根据业务来自行设计吧
const Webscoket: FC = () => {
  const [optionData, setOptionData] = useState<any[]>([])
  const [myChart, setMychart] = useState<any>()

  useEffect(() => {
    // initWebSocket();
    initEcharts()
    return () => {}
  }, [optionData])

  const initEcharts = async () => {
    // 基于准备好的dom，初始化echarts实例
    const myChart = echarts.init(document.getElementById("webscoket"))
    setMychart(myChart)
    // 绘制图表
    myChart.setOption(option)
  }

  const handleExport = () => {
    const imagesBase64 = myChart.getDataURL("png")
    // this.handleExcel(this.imagesBase64);
    console.log(`imagesBase64`, imagesBase64)
    handleExcel(imagesBase64)
  }

  const handleExcel = (base64Img: any) => {
    const EXCEL_TYPE =
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8"
    let workbook = new Excel.Workbook()
    workbook.creator = "Me"
    workbook.lastModifiedBy = "Her"
    workbook.created = new Date(1985, 8, 30)
    workbook.modified = new Date()
    workbook.lastPrinted = new Date()
    workbook.views = [
      {
        x: 0,
        y: 0,
        width: 1000,
        height: 2000,
        firstSheet: 0,
        activeTab: 1,
        visibility: "visible",
      },
    ]

    let worksheet = workbook.addWorksheet("sheet1")
    const imgArr = [base64Img] // 可以多张图片
    imgArr.forEach((item, index) => {
      const imageId1 = workbook.addImage({
        base64: item,
        extension: "png", // 图片扩展名，支持“jpeg”，“png”，“gif”
      })
      worksheet.addImage(
        imageId1,
        `${String.fromCharCode(65 + index * 6)}1:${String.fromCharCode(
          70 + index * 6
        )}16`
      )
    })
    workbook.xlsx.writeBuffer().then((data) => {
      const blob = new Blob([data], { type: EXCEL_TYPE })
      console.log(blob.stream(), 6664744)
      FileSaver.saveAs(blob, "download.xlsx")
    })
  }

  return (
    <div>
      <div id="webscoket">web</div>
      <button onClick={handleExport}>下载</button>
    </div>
  )
}
export default Webscoket
